package logic

import (
	"context"
	"time"

	myutils "googee/common/utils"
	"googee/service/leaderboard/rpc/internal/svc"
	"googee/service/leaderboard/rpc/internal/utils"
	"googee/service/leaderboard/rpc/types/leaderboard"

	"github.com/fatih/color"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type GetRankForUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetRankForUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRankForUserLogic {
	return &GetRankForUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  获得当个用户的排名
func (l *GetRankForUserLogic) GetRankForUser(in *leaderboard.UserRequest) (*leaderboard.UserResponse, error) {
	resp := &leaderboard.UserResponse{}

	//获得排行榜对象
	board, err := l.svcCtx.LeaderboardsModel.FindOne(l.ctx, in.Bid)
	if err != nil || board == nil {
		return nil, status.Error(codes.NotFound, "没有找到排行榜")
	}

	now := time.Now()
	if in.Batchid > 0 {
		now = time.Unix(in.Batchid, 0)
	}
	var batchid int64 = 1

	if board.Typ == "N" || board.Cron == "" {
		batchid = 1
	} else {
		prev := myutils.PrevCronTime(board.Cron, now)
		color.Red("prev=%v", prev)
		for i := 0; i < myutils.AbsInt(int(in.BatchOffset)); i++ {
			if in.BatchOffset < 0 {
				prev = myutils.PrevCronTime(board.Cron, prev.Add(-1*time.Second))
			} else {
				prev = myutils.NextCronTime(board.Cron, prev.Add(1*time.Second))
			}
			color.Red("prev=%v", prev)
		}
		batchid = prev.Unix()
	}

	rank, err := utils.RankForUser(l.svcCtx.SqlConn, l.ctx, in.Bid, in.UserId, batchid, in.Dense)
	if err == nil {
		resp.Rank = rank
	} else {
		resp.Rank = rank
	}

	resp.Batchid = batchid
	resp.UserId = in.UserId
	resp.Bid = in.Bid

	return resp, nil
}
